import { Select2Page } from "../../../common/serve-request.js";

(function (window, document, $) {
    let _vm, savetype, entriesmater, getEntryInfo = [], nextEntryId = 1, operaEntryId, saveEntry, checkSale;
    $(async function () {
        _vm = new Vue({
            el: "#salesentry-form",
            data() {
                return {
                    "entries": [
                        {
                            "seq": "",
                            "material": {
                                "id": "",
                                "numCode": "",
                                "name": "",
                                "model": "",
                                "fassistUnit": "",
                                "baseMeasureUnit": ""
                            },
                            "fassistQty": "",
                            "baseQty": "",
                            "remark": "",
                            "isGift": false
                        }
                    ],
                }
            },
            methods: {
                submit() {
                    savedata()
                }
            }
        });
        _initCommand()
        master()
        $(document).on('mousedown', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $(document).on('focus', '.clearContent', function (e) {
            e.target.style.fontSize = '16px';
        });
        $('body').attr('data-weui-theme', 'light'); //强制光明模式
    });
    // 初始化数据
    const _initCommand = () => {
        if (Utils.IsNotNull(getUrlKey('nextEntryId'))) {
            nextEntryId = getUrlKey('nextEntryId')
            $('.entry').text(`分录${nextEntryId}`)
        }
        else {
            $('.entry').text(`分录1`)
        }
        // 编辑分录
        if (Utils.IsNotNull(getUrlKey('operaEntryId'))) {
            $("title").text("编辑销售计划明细");
            operaEntryId = Number(getUrlKey('operaEntryId')) - 1
            _vm.entries.pop()
            _vm.entries.push(JSON.parse(Utils.GetSessionStorage("getEntryInfo"))[operaEntryId])
        }
        //取消按钮，返回列表
        $(document).on('click', '#returnMain', function () {
            if (Utils.IsNotNull(getUrlKey("id"))) {
                location.href = `../salesplan/addsalesplan.html?v=${Utils.GetTime()}&nextEntryId=${nextEntryId}&id=${getUrlKey("id")}`;
            }
            else {
                location.href = `../salesplan/addsalesplan.html?v=${Utils.GetTime()}&nextEntryId=${nextEntryId}`;
            }
        });
    }

    // 物料
    const master = () => {
        setTimeout(() => {
            Select2Page($(`#materialid`), `${Utils.CurDomain.MasterDataUrl}/yymaterials/q`, (params) => {
                return ({
                    Status: true,
                    SearchInfo: params.term,
                    pageSize: 10,
                    pageIndex: (params.page || 1) - 1
                })
            }, "GET", {
                placeholder: '请选择物料...', //默认文字提示
                templateResult: function (res) {
                    return `${res.name}(${res.numCode})`;
                }
            });
            $("#materialid").setSelectValue();

            $("#materialid").setSelectValue(_vm.entries[0].material.id, _vm.entries[0].material.name);
            $("#materialid").val(_vm.entries[0].material.id).trigger('change');

            $(`#materialid`).on('change', function () {
                // 渲染规格和基本单位
                $(`.material-model`).val($(`#materialid`).select2('data')[0]?.model)
                $(`.material-baseMeasureUnit`).val($(`#materialid`).select2('data')[0]?.baseMeasureUnit)
                _vm.entries[0].material.id = $('#materialid').select2('data')[0]?.id
                _vm.entries[0].material.name = $('#materialid').select2('data')[0]?.name
                _vm.entries[0].material.numCode = $('#materialid').select2('data')[0]?.numCode
                _vm.entries[0].material.model = $('#materialid').select2('data')[0]?.model
                _vm.entries[0].material.baseMeasureUnit = $('#materialid').select2('data')[0]?.baseMeasureUnit
                _vm.entries[0].material.fassistUnit = $('#materialid').select2('data')[0]?.fassistUnit
            })
        }, 200);
    }

    // 保存
    const savedata = () => {
        // 大于0的两位小数
        const reg = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/
        if (!Utils.IsNotNull($(`#materialid`).select2('data'))) {
            return $.toptip(`请选择物料!`, 'warning');
        }
        if (!Utils.IsNotNull($('#baseQty').val()) && !Utils.IsNotNull($('#fassistQty').val())) {
            return $.toptip(`请输入计划基本数量或计划辅助数量!`, 'warning');
        }
        if (Utils.IsNotNull($('#baseQty').val())) {
            if (!$(`#baseQty`).val().match(reg)) {
                return $.toptip(`计划基本数量必须是大于0的两位小数!`, 'warning');
            }
        }
        if (Utils.IsNotNull($('#fassistQty').val())) {
            if (!$(`#fassistQty`).val().match(reg)) {
                return $.toptip(`计划辅助数量必须是大于0的两位小数!`, 'warning');
            }
        }

        entriesmater = {
            "seq": Number(nextEntryId),
            "material": {
                "id": _vm.entries[0].material.id,
                "numCode": _vm.entries[0].material.numCode,
                "name": _vm.entries[0].material.name,
                "model": _vm.entries[0].material.model,
                "baseMeasureUnit": _vm.entries[0].material.baseMeasureUnit,
                "fassistUnit": _vm.entries[0].material.fassistUnit
            },
            "baseQty": $(`#baseQty`).val(),
            "fassistQty": $('#fassistQty').val(),
            "remark": $('#remark').val(),
            "isGift": $('#isGift').is(':checked')
        }
        if (Utils.IsNotNull(getUrlKey('operaEntryId'))) {
            entriesmater.seq = Number(getUrlKey('operaEntryId'))
        }
        if (Utils.IsNotNull(Utils.GetSessionStorage("getEntryInfo"))) {
            getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
        }
        checkSale = getEntryInfo
        // 编辑分录
        if (Utils.IsNotNull(getUrlKey("operaEntryId"))) {
            delete checkSale[operaEntryId]
        }
        // 过滤出和当前选择的一样的物料
        let checkSaleflag = checkSale.filter(function (item, index) {
            return item.material.id === entriesmater.material.id
        })
        if (Utils.IsNotNull(checkSaleflag)) {
            let flagfalse = checkSaleflag.some(item => {
                return item.isGift === false && $('#isGift').is(':checked') === false
            })
            let flagtrue = checkSaleflag.some(item => {
                return item.isGift === true && $('#isGift').is(':checked') === true
            })
            if (flagfalse || flagtrue) {
                return $.toptip(`物料重复,请重新选择!`, 'warning');
            }
            else {
                savetips()
            }
        }
        else {
            savetips()
        }

    }
    // 保存提示
    const savetips = () => {
        if (Utils.IsNotNull(getUrlKey("operaEntryId"))) {
            savetype = '修改'
            saveEntry = getUrlKey("operaEntryId")
        }
        else {
            savetype = '保存'
            saveEntry = getUrlKey('nextEntryId')
        }

        $.modal({
            autoClose: false,
            title: '提示',
            text: `<div class="weui-cells__group weui-cells__group_form" style="margin-top:-5px">
					<div class="" style="padding:5px;display:flex;justify-content: center; padding-bottom: 20px;">
						<div>是否确认${savetype}该分录？</div>
					</div>`,
            buttons: [
                {
                    text: "取消", className: "default", onClick: function () {
                        $.closeModal();
                    }
                },
                {
                    text: "保存", onClick: function () {
                        //先获取分录的内容
                        if (Utils.IsNotNull(Utils.GetSessionStorage("getEntryInfo"))) {
                            getEntryInfo = JSON.parse(Utils.GetSessionStorage("getEntryInfo"))
                        }
                        // 编辑分录
                        if (Utils.IsNotNull(getUrlKey("operaEntryId"))) {
                            // 存储下一个分录的序号
                            nextEntryId = Number(nextEntryId)
                            getEntryInfo[operaEntryId] = entriesmater
                            JSON.stringify(Utils.SetSessionStorage("getEntryInfo", getEntryInfo))
                        }
                        // 新增分录
                        else {
                            nextEntryId = Number(nextEntryId) + 1
                            getEntryInfo.push(entriesmater)
                            JSON.stringify(Utils.SetSessionStorage("getEntryInfo", getEntryInfo))
                        }
                        location.href = `./addsalesplan.html?v=${Utils.GetTime()}&nextEntryId=${nextEntryId}`;

                        if (Utils.IsNotNull(getUrlKey("id"))) {
                            location.href = `./addsalesplan.html?v=${Utils.GetTime()}&nextEntryId=${nextEntryId}&id=${getUrlKey("id")}`;
                        }
                        else {
                            location.href = `./addsalesplan.html?v=${Utils.GetTime()}&nextEntryId=${nextEntryId}`;
                        }
                        $.closeModal();
                    }
                }
            ]
        });
    }

    // 获取地址栏的参数
    const getUrlKey = (name) => {
        var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)", "i");
        var r = window.location.search.substr(1).match(reg);
        if (r != null) return unescape(r[2]); return null;
    }
    // 解决字段过长
    const cutstr = (str, len) => {
        var str_length = 0;
        var str_len = 0;
        var str_cut = new String();
        str_len = str.length;
        for (var i = 0; i < str_len; i++) {
            var a = str.charAt(i);
            str_length++;
            if (escape(a).length > 4) {
                //中文字符的长度经编码之后大于4 
                str_length++;
            }
            str_cut = str_cut.concat(a);
            if (str_length >= len) {
                str_cut = str_cut.concat("...");
                return str_cut;
            }
        }
        //如果给定字符串小于指定长度，则返回源字符串； 
        if (str_length < len) {
            return str;
        }
    }
})(window, document, jQuery)